#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include <GLFW/glfw3.h>
#include <thread>
#include <atomic>
#include <cstdio>


// 1. 算法参数集合 ============================
struct Param {
    float  blur     = 5.0f;      // 高斯核半径
    int    thresh   = 128;       // 二值化阈值
    bool   showHelp = true;
};
// 为了让“面板”与“算法”解耦，这里放一份全局原子副本
static Param g_param;                    // 主线程 <=> GUI 读写
static std::atomic<bool> g_paramChanged{true};


// 2. 算法线程（伪代码：打印参数） ============
void algorithmThread()
{
    Param local;
    while (true) {
        if (g_paramChanged.exchange(false)) {
            local = g_param;          // 原子拷贝
            printf("【算法】blur=%.3f  thresh=%d\n", local.blur, local.thresh);
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }
}


// 3. Dear ImGui 面板 =========================
void drawGuiPanel()
{
    ImGui::Begin("参数面板");
    bool changed = false;
    changed |= ImGui::SliderFloat("blur", &g_param.blur, 0.1f, 20.0f);
    changed |= ImGui::SliderInt("thresh", &g_param.thresh, 0, 255);
    changed |= ImGui::Checkbox("show help", &g_param.showHelp);
    if (changed) g_paramChanged = true;
    if (g_param.showHelp)
        ImGui::TextWrapped("拖动滑块即可实时改参，算法线程立即生效");
    ImGui::End();
}


// 4. 主函数：窗口 + 主循环 ==================
int main()
{
    glfwInit();
    GLFWwindow* win = glfwCreateWindow(1280, 720, "ImGui 动态调参", nullptr, nullptr);
    glfwMakeContextCurrent(win);
    glfwSwapInterval(1);
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO();
    ImFontConfig font_cfg;
    font_cfg.FontNo = 0; // 尝试加载ttc文件的第一个字体
    io.Fonts->AddFontFromFileTTF("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", 20.0f, &font_cfg, io.Fonts->GetGlyphRangesChineseFull());
    ImGui_ImplGlfw_InitForOpenGL(win, true);
    ImGui_ImplOpenGL3_Init("#version 130");
    std::thread algo(algorithmThread);
    while (!glfwWindowShouldClose(win)) {
        glfwPollEvents();
        ImGui_ImplOpenGL3_NewFrame();
        ImGui_ImplGlfw_NewFrame();
        ImGui::NewFrame();
        drawGuiPanel();          // 每帧都把面板画出来
        ImGui::Render();
        int w, h;
        glfwGetFramebufferSize(win, &w, &h);
        glViewport(0, 0, w, h);
        glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
        glfwSwapBuffers(win);
    }
    algo.join();
    ImGui_ImplOpenGL3_Shutdown();
    ImGui_ImplGlfw_Shutdown();
    ImGui::DestroyContext();
    glfwDestroyWindow(win);
    glfwTerminate();
}